package models

import (
	"fmt"
	"github.com/zw2582/ginlib"
	"time"
)

//IdnameLogRequest 身份证实名认证请求日志
type IdnameLogRequest struct {
	Id uint `xorm:"pk autoincr"`
	AccountId int `xorm:"comment('账户id')"`
	Uuid string `xorm:"unique varchar(32)"`
	Name string
	IdCard string `xorm:"varchar(20)"`
	Sign string `xorm:"varchar(32)"`
	Code int `xorm:"int"`
	Fake uint `xorm:"comment('发生重大错误，正在用兜底假数据')"`
	Error string `xorm:"text"`
	Duration int64 `xorm:"int comment('耗时（毫秒）')"`
	FromCache int `xorm:"comment('0.通道校验 1.来自缓存 2.本地校验')"`
	Price float64 `xorm:"decimal(12,2) comment('单价*元')"`
	CreatedAt time.Time `xorm:"created"`
	UpdatedAt time.Time `xorm:"updated"`
}

func init()  {
	ginlib.XormAddWaitSync(new(IdnameLogRequest))
}

func (this *IdnameLogRequest) Save() {
	if this.Id == 0 {
		if this.Uuid == "" {
			panic("请传递uuid")
		}
		obj := RequestLogGetByUuid(this.Uuid)
		this.Id = obj.Id
	}

	var err error
	if this.Id == 0 {
		_, err = DB.Insert(this)
	} else {
		_, err = DB.ID(this.Id).Update(this)
	}

	if this.Fake == 1 {
		//发送邮件通知
		f := fmt.Sprintf("发生致命错误，目前使用假数据兜底，请快速修复！！！\nuuid:%s\nname:%s\nidcard:%s\nlast_error:%s\n", this.Uuid, this.Name, this.IdCard, this.Error)
		SmtpUtilDefault.SendToMail("2582308253@qq.com", ginlib.APP_NAME+" 严重错误_idname", f, "text")
	}

	if err != nil {
		panic(err)
	}

	//一致的情况下保存id数据
	if this.FromCache == 0 && this.Code == RC_ID_YIZHI.Code() {
		IdDataSave(this.Name, this.IdCard)
	}
}

func RequestLogGetByUuid(uuid string) (obj IdnameLogRequest) {
	DB.Where("uuid=?", uuid).Get(&obj)
	return
}
